# -*- coding: utf-8 -*-
"""
@Time    : 2022/2/7 15:28
@Author  : Corey
"""


class MapResultCenter:
    def __init__(self, pos_data_dict, pos_id_dict, pos_list):
        super(MapResultCenter, self).__init__()
        self.pos_data_dict = pos_data_dict
        self.pos_id_dict = pos_id_dict
        self.pos_list = pos_list

    def _handle_raw_data(self):
        """
        自动补全坐标
        :param pos_list: [(x,y),(x,y)]
        :return: pos_broken_list->补全后pos list, pos_x->x范围, pos_y->y范围
        """
        global max_last_index, max_first_index, pos_x
        index_first = self.pos_list[0][1]
        index_last = self.pos_list[-1][1]
        pos_y = [index_first, index_last]
        pos_cal_list = []
        for i in range(index_first, index_last + 1):
            current_list = []
            for z in self.pos_list:
                if z[1] == i:
                    current_list.append(z)
            pos_cal_list.append(current_list)
        if pos_cal_list:
            for i in pos_cal_list:
                i.sort()
            min_set = set()
            max_set = set()
            for k in pos_cal_list:
                if k:
                    min_set.add(k[0][0])
                    max_set.add(k[-1][0])
            pos_x = [min(min_set), max(max_set)]
            max_len = pos_x[1] - pos_x[0] + 1
            print(max_len)
            pos_broken_list = []
            for z in pos_cal_list:
                current_broken_list = []
                if z:  # 判空行
                    for k in range(pos_x[0], pos_x[1] + 1):
                        current_broken_list.append([k, z[0][1]])
                pos_broken_list.append(current_broken_list)
            return self._display_data(pos_broken_list, pos_x, pos_y, max_len)  # 开始处理修补数据
        else:
            return None, None, None, None

    def _display_data(self, pos_broken_list, pos_x, pos_y, max_len):  # pos_broken_list, pos_x, pos_y
        value_list = []
        id_list = []
        for z in pos_broken_list:
            # 判断值是否是实际坐标，如果不是就添加假值
            value_row = []
            id_row = []
            if z:
                for j in z:
                    pos_str = str((j[0], j[1]))
                    if pos_str in self.pos_data_dict:  # pos_data_dict存储实际pos value ->{"(x,y)":value}
                        value = float(self.pos_data_dict[pos_str])
                        value_row.append(value)
                        id_row.append(self.pos_id_dict[pos_str])
                    else:
                        value_row.append(-300)  # 假值
                        id_row.append(-300)

            else:
                for _ in range(max_len):
                    value_row.append(-300)  # 假值
                    id_row.append(-300)

            value_list.append(value_row)
            id_list.append(id_row)
        return value_list, id_list, pos_x, pos_y, pos_broken_list

    # 写矩阵数据到txt文件
    def _save_bin_data_2_txt(self, file_path, value_list):
        count1 = self.count_list(value_list)
        count = dict(sorted(count1.items()))
        new_list = []
        for key, value in count.items():
            item = [key, value, value / sum(count.values())]
            new_list.append(item)
        total_pass = list(count.values())[0]
        total_tested = sum(count.values())
        total_fail = total_tested - total_pass
        yield_count = total_pass / total_tested

        with open(file_path, "w", encoding='utf-8') as f:
            f.write(f"Total Pass   : {total_pass}")
            f.write("\n")
            f.write(f"Total Fail   : {total_fail}")
            f.write("\n")
            f.write(f"Total Tested : {total_tested}")
            f.write("\n")
            f.write(f"Yield        : {round(yield_count * 100, 2)}%")
            f.write("\n")
            f.write("\n")
            f.write("BINNAME, DIENUM, YIELD")
            f.write("\n")
            for item in new_list:
                f.write(f"Bin, {int(item[0])},{item[1]},{round(item[2] * 100, 2)}%")
                f.write("\n")
            f.write("\n")
            f.write("\n")
            for i in range(len(value_list)):
                for j in value_list[i]:
                    if j == -300:
                        f.write(".")
                    else:
                        f.write(str(int(j)))
                f.write("\n")

    def count_list(self, std: list):
        import itertools
        out = list(itertools.chain.from_iterable(std))
        from collections import Counter
        name = Counter()
        for num in out:
            if num != -300:
                name[num] += 1
        return name
